using System;
using System.Reflection;
using Microsoft.Practices.Unity;

namespace Core.IocHelpers
{
  ///<summary></summary>
  public static class AutoRegister
  {
    ///<summary>Scans the executing and calling assemblies, and registers each implementation marked with AutoRegister.</summary>
    ///<param name="container"></param>
    public static void DoAutoRegistrations(IUnityContainer container)
    {
      //DoAutoRegistrations(container, Assembly.GetExecutingAssembly());
      DoAutoRegistrations(container, Assembly.GetCallingAssembly());
    }

    ///<summary>Auto register this assembly</summary>
    ///<param name="container"></param>
    ///<param name="assembly"></param>
    public static void DoAutoRegistrations(IUnityContainer container, Assembly assembly)
    {
      foreach (var module in assembly.GetModules(true))
      {
        foreach (var type in module.GetTypes())
        {
          if (Attribute.GetCustomAttribute(type, typeof (AutoRegisterAttribute)) != null)
          {
            var interfaces = type.GetInterfaces();
            if (interfaces.Length == 0)
              continue;

            foreach (var i in interfaces)
            {
              if (Attribute.GetCustomAttribute(i, typeof (AutoRegisterableAttribute)) != null)
              {
                //if (container.Resolve(i) != null)
                //{
                //  throw new Exception(string.Format("Attempting to register two implementations for one interface: {0}", i));
                //}
                container.RegisterType(i, type); //, string.Format("{0}-->{1}", i, t));
              }
            }
          }
        }
      }
    }
  }
}